#include "Tileset.hpp"
#include <fstream>
using namespace std;

void Tileset::load(string img)
{
	m_text = TextureManager::Instance()->Get(img);
	m_width = m_text->getSize().x / 16;
	m_height = m_text->getSize().y / 16;
}

void Tileset::loadCollisionMask(string path)
{
	m_collisionMask.clear();
	ifstream file;
	file.open(path.c_str());
	if(file.is_open())
	{
		while(file.good())
		{
			unsigned int value;
			file>>value;
			if(!file.fail())
				m_collisionMask.push_back(value);
			else
				throw string("Error while loading the tileset collision mask data.");
		}
	}
	else
		throw string("Unable to load the tileset collision mask data.");
	if(m_collisionMask.size() != m_width*m_height)
		throw string("Bad size of tileset collision mask data.");
}

void Tileset::setSprite(sf::Sprite& sprite, unsigned int tile)
{
	sprite.setTexture(*m_text);
	if(tile < m_width * m_height)
	{
		sprite.setTextureRect(sf::IntRect((tile%m_width)*16,(tile/m_width)*16,16,16));
	}
	else
	{
		sprite.setTextureRect(sf::IntRect(0,0,16,16)); //default is 0
	}
}

bool Tileset::checkColliding(unsigned int tile)
{
	if(tile < m_collisionMask.size() && m_collisionMask[tile] > 0)
		return true;
	else
		return false;
}
